<template>
  <div class="page-wrapper">
    <!-- Page body -->
    <div class="page-body">
      <div class="container-xl">
        <div class="row row-deck row-cards">
          <div class="col-12">
            <div class="card">
              <div class="card-header">
                <div class="row g-2 align-items-center">
                  <div class="col-6 col-sm-4 col-md-2 col-xl py-0">
                    <a href="#" class="btn btn-primary w-100" @click="openAddPluginLabel"
                       data-bs-target="#modal-add-plugin-label">
                      新增插件标签
                    </a>
                  </div>
                  <div class="col-6 col-sm-4 col-md-2 col-xl py-0">
                    <a href="#" class="btn btn-info w-100" @click="openEditPluginLabel">
                      修改插件标签
                    </a>
                  </div>
                  <div class="col-6 col-sm-4 col-md-2 col-xl py-0">
                    <a href="#" class="btn btn-danger w-100" @click="confirmDelete">
                      删除插件标签
                    </a>
                  </div>
                  <div class="col-6 col-sm-4 col-md-2 col-xl py-0">
                    <a href="#" class="btn btn-warning w-100" @click="changePluginTypeStatus('启用', 1)">
                      启用
                    </a>
                  </div>
                  <div class="col-6 col-sm-4 col-md-2 col-xl py-0">
                    <a href="#" class="btn btn-secondary w-100" @click="changePluginTypeStatus('禁用', 0)">
                      禁用
                    </a>
                  </div>
                </div>
              </div>
              <div class="card-body border-bottom py-3">
                <div class="d-flex">
                  <div class="text-secondary">
                    {{ tableData.length }} 个插件标签
                  </div>
                  <div class="ms-auto text-secondary">
                    搜索:
                    <div class="ms-2 d-inline-block">
                      <input type="text" class="form-control form-control-sm" aria-label="Search plugin label"
                             placeholder="预留框，暂时无用">
                    </div>
                  </div>
                </div>
              </div>
              <div class="table-responsive">
                <table class="table card-table table-vcenter text-nowrap datatable">
                  <thead>
                  <tr>
                    <th><input class="form-check-input m-0 align-middle" type="checkbox" v-model="isAllChecked"
                               @change="handleToggleAllCheckboxes"></th>
                    <th class="w-1">ID</th>
                    <th>类型名称</th>
                    <th>标签类型</th>
                    <th>备注</th>
                    <th>状态</th>
                    <th>最后更新时间</th>
                  </tr>
                  </thead>
                  <tbody>
                  <tr v-for="(item, index) in tableData" :key="index" @click="toggleRowCheckbox(item)"
                      :class="{'selected-row': item.checked}">
                    <td><input class="form-check-input m-0 align-middle" type="checkbox" v-model="item.checked" @click.stop></td>
                    <td><span class="text-secondary">{{ item.id }}</span></td>
                    <td>{{ item.name }}</td>
                    <td>{{ item.labelType }}</td>
                    <td :title="item.remark">
                      {{ truncateText(item.remark, 30) }}
                    </td>
                    <td>
                      <span :class="{
                        'badge': true,
                        'bg-green-lt': item.enabled === 1,
                        'bg-red-lt': item.enabled === 0
                      }">
                        {{ item.enabled === 1 ? '启用' : (item.enabled === 0 ? '禁用' : item.enabled) }}
                      </span>
                    </td>
                    <td>{{ item.lastUpdateTime }}</td>
                  </tr>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 使用封装的模态框组件 -->
  <ComponentModal
      :modalId="'modal-success-plugin-label'"
      :title="'信息'"
      :message="'操作成功'"
      :cancelText="'取消'"
      :confirmText="'确定'"
      ref="componentModalOutRef"
  />

  <AddPluginLabelModal ref="addPluginLabelModalRef"/>
  <EditPluginLabelModal ref="editPluginLabelModalRef"/>
  <Loading ref="loadingRef"/>
</template>

<script setup>
import {ref, reactive, onMounted, computed, inject, nextTick, onUnmounted, watch} from 'vue';
import { useRoute } from 'vue-router';
import ComponentModal from '@/components/ComponentModal.vue';
import Loading from '@/components/Loading.vue';
import AddPluginLabelModal from "./AddPluginLabelModal.vue";
import EditPluginLabelModal from "./EditPluginLabelModal.vue";
import { useTableMixin } from '@/mixins/tableMixin';

const apiBaseUrl = import.meta.env.VITE_API_BASE_URL;
// 表格数据和分页信息
const tableData = ref([]);
const isAllChecked = ref(false);

const addPluginLabelModalRef = ref(null);
const componentModalOutRef = ref(null);
const loadingRef = ref(null);
const editPluginLabelModalRef = ref(null);

const { 
  toggleAllCheckboxes,
  toggleRowCheckbox,
  getSelectedIds,
  hasSelectedItems,
  resetSelection 
} = useTableMixin();

const route = useRoute();

// 查询数据的函数
const fetchData = async () => {
  if (!loadingRef.value) {
    console.warn('Loading component not initialized yet');
    return;
  }

  try {
    loadingRef.value.openLoading();
    const response = await fetch(apiBaseUrl + '/resident/plugin-label/search');
    const data = await response.json();
    
    if (data.success) {
      tableData.value = data.result;
    } else {
      componentModalOutRef.value?.openWarnModal(data.message || '加载插件标签数据失败');
    }
  } catch (error) {
    console.error('Error fetching data:', error);
    componentModalOutRef.value?.openWarnModal('加载插件标签数据失败，请稍后重试！');
  } finally {
    loadingRef.value?.closeLoading();
  }
}

// 监听路由变化
watch(() => route.path, (newPath) => {
  console.log('当前路由路径:', newPath);
  if (newPath === '/resident-web/plugins-setting' || newPath === '/plugins-setting') {
    console.log('进入插件标签页面，开始加载数据');
    // 延迟执行 fetchData，确保组件已挂载
    nextTick(() => {
      fetchData();
    });
  }
}, { immediate: true });

// 启用,禁用
const changePluginTypeStatus = (text, status) => {
  let ids = [];
  tableData.value.forEach(item => {
    if (item.checked) {
      ids.push(item.id);
    }
  });
  if (ids.length > 0) {
    const idStr = ids.join(',');
    componentModalOutRef.value.openWarnModal(`确定${text} ${idStr} 的插件标签吗?`, async () => {
      try {
        const formData = new URLSearchParams();
        formData.append('typeIds', idStr);
        formData.append('status', status);

        const response = await fetch(`${apiBaseUrl}/resident/plugin-label/status`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
          },
          body: formData
        });
        const data = await response.json();
        if (data.success) {
          componentModalOutRef.value.openInfoModal(`${text}成功！`);
        }
      } catch (error) {
        componentModalOutRef.value.openWarnModal(`${text}失败！`);
      }
      fetchData();
    });
  } else {
    componentModalOutRef.value.openWarnModal('请选择需要操作的元素');
  }
}

// 处理全选/全不选逻辑
const handleToggleAllCheckboxes = () => {
  toggleAllCheckboxes(tableData.value, isAllChecked.value);
};

// 监听表格数据变化，更新全选状态
watch(tableData, () => {
  isAllChecked.value = tableData.value.length > 0 && tableData.value.every(item => item.checked);
}, { deep: true });

// 处理行选择
const handleRowCheckbox = (item) => {
  toggleRowCheckbox(tableData.value, item);
};

// 处理行点击
const handleRowClick = (item) => {
  handleRowCheckbox(item);
};

// 处理确认删除事件
const confirmDelete = () => {
  const delIds = getSelectedIds(tableData.value);
  if (delIds.length > 0) {
    componentModalOutRef.value.openWarnModal('确定删除' + delIds.join(', ') + '的插件标签吗?', async () => {
      try {
        let deleteUrl = apiBaseUrl + '/resident/plugin-label/delete?typeIds=' + delIds.join(',');
        const response = await fetch(deleteUrl, {
          method: 'DELETE'
        });
        const data = await response.json();
        if (data.success) {
          componentModalOutRef.value.openInfoModal('删除成功！');
          fetchData(); // 刷新列表
        } else {
          componentModalOutRef.value.openWarnModal('删除失败：' + (data.message || '未知错误'));
        }
      } catch (error) {
        console.error('Delete error:', error);
        componentModalOutRef.value.openWarnModal('删除失败，请稍后重试！');
      }
    });
  } else {
    componentModalOutRef.value.openWarnModal('请选择需要删除的插件标签');
  }
};

const openAddPluginLabel = () => {
  addPluginLabelModalRef.value.openModal();
}

const openEditPluginLabel = () => {
  const selectedItems = tableData.value.filter(item => item.checked);
  if (selectedItems.length !== 1) {
    componentModalOutRef.value.openWarnModal('请选择一条记录进行修改');
    return;
  }
  editPluginLabelModalRef.value.openModal(selectedItems[0]);
};

// 添加文本截断函数
const truncateText = (text, length) => {
  if (!text) return '';
  return text.length > length ? text.substring(0, length) + '...' : text;
};

onMounted(() => {
  console.log('组件已挂载，当前路径:', route.path);
  // 如果当前路径是插件标签页面，则加载数据
  if (route.path === '/resident-web/plugins-setting' || route.path === '/plugins-setting') {
    fetchData();
  }
  // 添加事件监听器
  window.addEventListener('plugin-label-added', fetchData);
  window.addEventListener('plugin-label-updated', fetchData);
});

// 在组件卸载时移除事件监听器
onUnmounted(() => {
  window.removeEventListener('plugin-label-added', fetchData);
  window.removeEventListener('plugin-label-updated', fetchData);
});
</script>

<style scoped>
/* 状态样式 */
.bg-green-lt {
  background-color: rgba(40, 167, 69, 0.15) !important;
  color: #2fb344 !important;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.875em;
}

.bg-red-lt {
  background-color: rgba(220, 53, 69, 0.15) !important;
  color: #d63939 !important;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.875em;
}

/* 表格样式优化 */
.table td {
  padding: 0.75rem;
  vertical-align: middle;
}

.table th {
  font-weight: 600;
  background-color: #f8f9fa;
  border-bottom: 2px solid #dee2e6;
}

.badge {
  display: inline-block;
  font-weight: 500;
  line-height: 1.2;
  text-align: center;
  white-space: nowrap;
  vertical-align: baseline;
}

/* 添加描述列的样式 */
td[title] {
  cursor: help;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 添加选中行的样式 */
.selected-row {
  background-color: rgba(32, 107, 196, 0.1) !important;
}

tr {
  cursor: pointer;
  transition: background-color 0.2s ease;
}

tr:hover {
  background-color: rgba(32, 107, 196, 0.05);
}

/* 防止点击复选框时触发行点击事件 */
tr input[type="checkbox"] {
  cursor: pointer;
  pointer-events: auto;
}

.btn-danger {
  background-color: #d63939;
  border-color: #d63939;
  color: #fff;
}

.btn-danger:hover {
  background-color: #c82333;
  border-color: #bd2130;
}

.btn-info {
  background-color: #0dcaf0;
  border-color: #0dcaf0;
  color: #fff;
}

.btn-info:hover {
  background-color: #31d2f2;
  border-color: #25cff2;
}
</style> 